/**
 * 
 */
package edu.umd.clip.lm.storage.remote;

import java.nio.ByteBuffer;
import java.io.*;

import edu.umd.clip.lm.factors.FactorTuple;
import edu.umd.clip.lm.model.OnDiskCompactProbTree;
import edu.umd.clip.lm.model.ProbTree;

/**
 * @author Denis Filimonov <den@cs.umd.edu>
 *
 */
public class SingleTreeResponseMessage extends Message {
	private OnDiskCompactProbTree probTree;
	
	public SingleTreeResponseMessage(OnDiskCompactProbTree probTree, int modelId, int replyTo) {
		super(MessageHeader.SINGLE_TREE_RESPONSE, modelId);
		setReplyTo(replyTo);
		this.probTree = probTree;
	}
	
	public SingleTreeResponseMessage(MessageHeader header, ByteBuffer buffer) {
		super(header);
		readBody(buffer);
	}
	
	protected void readBody(ByteBuffer buffer) {
		try {
			ObjectInputStream in = new ObjectInputStream(new ByteArrayInputStream(buffer.array()));
			probTree = new OnDiskCompactProbTree(in);
		} catch (IOException e) {
			e.printStackTrace();
		} catch (ClassNotFoundException e) {
			e.printStackTrace();
		}
	}
	
	protected ByteBuffer writeBody() {
		ByteArrayOutputStream data = new ByteArrayOutputStream(4096);
		ObjectOutputStream out;
		try {
			out = new ObjectOutputStream(data);
			probTree.writeExternal(out);
			out.close();
		} catch (IOException e) {
			e.printStackTrace();
		}
		byte bytes[] = data.toByteArray();
		ByteBuffer buffer = ByteBuffer.wrap(bytes);
		return buffer;
	}

	public OnDiskCompactProbTree getProbTree() {
		return probTree;
	}
	
}
